<template>
  <main class="container" v-if="isLogin">
    <main class="content">
      <!-- 商品模块 -->
      <div class="goods_list" v-if="list.length > 0">
        <van-swipe-cell v-for="item in list" :key="item.id" class="goods_item">
          <van-checkbox v-model="item.checked" class="selected"></van-checkbox>
          <div class="goods_box">
            <van-card
              class="goods_card"
              :num="item.count"
              :price="((item.goods_info.price / 100) * item.count).toFixed(2)"
              :desc="item.goods_info.brand"
              :title="item.goods_info.name"
              :thumb="item.goods_info.pic_url"
            >
              <template #tags>
                <van-tag plain type="primary">{{
                  item.goods_info.tags
                }}</van-tag>
              </template>
              <template #footer>
                <!-- 计数器 -->
                <van-stepper @change="countChange(item)" v-model="item.count" />
              </template>
            </van-card>
          </div>
          <template #right>
            <van-button
              @click="deleteGoods(item.id)"
              square
              class="delete-button"
              type="danger"
              >删除</van-button
            >
          </template>
        </van-swipe-cell>
      </div>
      <!-- 空 -->
      <div v-else>
        <van-empty description="当前购物车无商品">
          <van-button
            @click="router.replace('/home')"
            round
            type="primary"
            class="bottom-button"
            >去首页</van-button
          >
        </van-empty>
      </div>
    </main>
    <!-- 底部 提交订单 -->
    <van-submit-bar
      v-if="list.length > 0"
      class="submit"
      :price="countPrice"
      button-text="提交订单"
      @submit="onSubmit"
    >
      <van-checkbox :checked="isAllChecked" @click="checkedAll"
        >全选</van-checkbox
      >
    </van-submit-bar>
  </main>
  <div v-else class="container">
    <van-empty description="请先登录">
      <van-button @click="router.replace('/login')" round type="primary" style="width:200px">去登录</van-button>
    </van-empty>
  </div>
</template>

<script setup>
import useCartInfo from "@/stores/useCartInfo";
import { cartEdit, cartDelete } from "@/api/cart";
import { showConfirmDialog, showSuccessToast } from "vant";
import { computed,ref } from "vue";
import { storeToRefs } from "pinia";
import { useRouter } from "vue-router";
import { getToken } from "@/utils/token";

// 是否登录
let isLogin = ref(!!getToken());

//路由器实例
let router = useRouter();
//购物车仓库 实例
let cartStore = useCartInfo();

// 仓库内 结构出 响应式 list
let { list } = storeToRefs(cartStore);

// 修改 购物车商品数量
let countChange = async (item) => {
  // 调用修改 购物车接口  传递  当前商品在购物车内的id  商品id  和修改的数量
  await cartEdit({ id: item.id, goods_id: item.goods_id, count: item.count });
};
// 删除购物车内 商品
let deleteGoods = (id) => {
  showConfirmDialog({
    title: "确认删除",
    message: "是否确认删除 该商品",
  })
    .then(async () => {
      //   确定 执行删除逻辑
      await cartDelete({ ids: [id] });
      // 重新获取 最新的 购物车数据
      cartStore.getCartInfo();
      showSuccessToast("删除成功");
    })
    .catch(() => {
      // on cancel
    });
};

// 计算 是否所有商品被选中
// 计算属性  也是 ref对象
let isAllChecked = computed(() => {
  // 判断 是否 所有商品的checked为true
  return list.value.every((item) => item.checked === true);
});

// 全选  反选 操作
let checkedAll = () => {
  // 当前全选 则 变为 false  非全选 则全改为true
  let bol = !isAllChecked.value;
  // 遍历 list  让内部checked值 全部切换
  list.value.forEach((item) => {
    item.checked = bol;
  });
};

// 计算选中的商品总价值
let countPrice = computed(() => {
  let num = 0;
  // 过滤出选中的商品
  let arr = list.value.filter((item) => item.checked);
  // console.log(arr);
  // 遍历 每个 选中商品 计算数量*单价
  arr.forEach((item) => {
    num = num + item.count * item.goods_info.price;
  });
  return num;
});
// 点击提交订单
let onSubmit=()=>{
  // 判断 是否有选中商品  checkedList是已经选中的购物车数据
  let checkedList=list.value.filter((item)=>item.checked)
  // 拿到选中的 购物车数据id
  let ids=checkedList.map(item=>item.id)
  // 传递给路由的参数  不能是引用数据类型 需要是字符串
  if(checkedList.length){
    // 跳转至地址选择
    router.push(`/address-list?isCart=1&checkedGoods=${ids}`)
  }else{
    showSuccessToast("请先选择商品");
  }
}
</script>

<style scoped lang="scss">
.delete-button {
  height: 100%;
}

.container {
  .login_btn {
    width: 280px;
  }
  main.content {
    margin-bottom: var(--van-submit-bar-height);
    .bottom-button {
      width: 200px;
    }
    .goods_list {
      .goods_item {
        position: relative;
        .selected {
          position: absolute;
          z-index: 2;
          left: 8px;
          top: 46px;
        }
        .goods_box {
          background: #f7f8fa;
          margin-top: 10px;
          .goods_card {
            margin-left: 30px;
          }
        }
        .delete-button {
          width: 100%;
          height: 100%;
        }
      }
    }
    .is_null {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      height: 55vh;
      text-align: center;
      p.cart_tip {
        font-size: 18px;
      }
      .to_btn {
        margin-top: 16px;
        width: 180px;
      }
    }
  }
  .submit {
    bottom: var(--van-submit-bar-height);
  }
}
</style>